<script lang="ts" setup>
import type { Connection, Edge, EdgeMouseEvent, Node, NodeMouseEvent } from '@vue-flow/core';
import { VueFlow, useVueFlow } from '@vue-flow/core';
import { Background } from '@vue-flow/background';
import { Controls } from '@vue-flow/controls';
import { MiniMap } from '@vue-flow/minimap';
import { defineEmits, defineProps } from 'vue';

const { addEdges } = useVueFlow();

const props = defineProps<{
  nodes: Node[];
  edges: Edge[];
}>();

const emit = defineEmits(['node-click', 'edge-click', 'nodes-change', 'edges-change', 'add-node']);

const onDrop = (event: DragEvent) => {
  if (!event.dataTransfer) return;

  const nodeData = JSON.parse(event.dataTransfer?.getData('application/json') || '{}');

  if (!nodeData) return;

  const { project } = useVueFlow();
  const flowContainer = document.querySelector('.vue-flow'); // 获取画布容器
  if (!flowContainer) return;
  const containerRect = flowContainer.getBoundingClientRect();
  const mouseX = event.clientX - containerRect.left;
  const mouseY = event.clientY - containerRect.top;

  // 应用偏移量（让鼠标位置成为节点中心）
  const position = project({
    x: mouseX - nodeData.offset?.width / 2,
    y: mouseY - nodeData.offset?.height / 2
  });
  emit('add-node', nodeData.type, position);
};

const onDragOver = (event: DragEvent) => {
  event.preventDefault();
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move';
  }
};

const onNodeClick = (event: NodeMouseEvent) => {
  emit('node-click', event.node);
};

const onEdgeClick = (event: EdgeMouseEvent) => {
  emit('edge-click', event.edge);
};

// 处理有效连接
const isValidConnection = (_connection: Connection) => {
  // 添加你的验证逻辑
  return true;
};

// 处理连线创建
const onConnect = (params: Connection) => {
  const newEdge: Edge = {
    id: `edge-${params.source}-${params.target}`,
    source: params.source,
    target: params.target,
    animated: true,
    style: { stroke: '#333' }
  };

  addEdges(newEdge);

  emit('edges-change', {
    type: 'add',
    item: newEdge
  });
};
</script>

<template>
  <div class="flow-container">
    <VueFlow
      class=""
      :nodes="props.nodes"
      :edges="props.edges"
      :connection-radius="10"
      :nodes-draggable="true"
      :nodes-connectable="true"
      :snap-to-grid="true"
      :grid-gap="20"
      :is-valid-connection="isValidConnection"
      @node-click="onNodeClick"
      @edge-click="onEdgeClick"
      @dragover.prevent
      @drop="onDrop"
      @dragover="onDragOver"
      @connect="onConnect"
    >
      <template #node-start="{ type }">
        <PorFlowNode :type="type" />
      </template>

      <template #node-end="{ type }">
        <PorFlowNode :type="type" />
      </template>
      <template #node-task="{ type }">
        <PorFlowNode :type="type" />
      </template>
      <template #node-inclusive="{ type }">
        <PorFlowNode :type="type" />
      </template>

      <template #node-exclusive="{ type }">
        <PorFlowNode :type="type" />
      </template>
      <template #node-parallel="{ type }">
        <PorFlowNode :type="type" />
      </template>

      <Controls class="flow-controls" position="top-right" />
      <MiniMap class="flow-minimap" position="bottom-right" />

      <Background pattern-color="#aaa" :gap="20" />
    </VueFlow>
  </div>
</template>

<style>
.flow-container {
  width: 100%;
  height: 100%;
}

/* 控制按钮组样式（右上角） */
.flow-controls {
  top: 1rem !important;
  right: 1rem !important;
  transform: none !important;
}

/* 缩略图样式（右下角） */
.flow-minimap {
  bottom: 10rem !important; /* 改为底部定位 */
  right: 1rem !important; /* 右侧定位 */
  top: auto !important; /* 取消顶部定位 */
  transform: none !important;
  left: auto !important; /* 取消左侧定位 */
}
</style>
